<template>
  <div class="app-container">
    <el-card class="search-card" shadow="never">
      <!-- 搜索操作 -->
      <template #header>
        <div class="card-header">
          <span>筛选条件</span>
          <el-button
            class="collapse-btn"
            type="text"
            @click="toggleSearch"
            :icon="showSearch ? 'ArrowDownBold' : 'ArrowUpBold'"
          >
            {{ showSearch ? "收起" : "展开" }}
          </el-button>
        </div>
      </template>

      <!-- 查询条件 -->
      <el-form
        :model="queryParams"
        ref="userShopRelationRef"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input
            v-model="queryParams.userId"
            placeholder="请输入用户ID"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="门店ID" prop="shopId">
          <el-input
            v-model="queryParams.shopId"
            placeholder="请输入门店ID"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="是否默认门店" prop="isDefault">
          <el-select
            v-model="queryParams.isDefault"
            placeholder="请选择是否默认门店"
            clearable
          >
            <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表单按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ruoyi:userShopRelation:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyi:userShopRelation:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyi:userShopRelation:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ruoyi:userShopRelation:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="userShopRelationList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="关联ID" align="center" prop="relationId" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="门店ID" align="center" prop="shopId" />
      <el-table-column label="是否默认门店" align="center" prop="isDefault">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.isDefault" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:userShopRelation:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:userShopRelation:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户门店关联信息对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
      class="user-shop-dialog"
    >
      <div class="dialog-content">
        <el-form
          ref="userShopRelationRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="dialog-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="选择用户"
                prop="userId"
                class="form-item-enhanced"
              >
                <el-select
                  v-model="form.userId"
                  placeholder="请选择用户"
                  filterable
                  clearable
                  remote
                  :remote-method="searchUser"
                  :loading="userLoading"
                  class="enhanced-select"
                >
                  <el-option
                    v-for="user in userOptions"
                    :key="user.userId"
                    :label="`${user.userName} (${user.nickName})`"
                    :value="user.userId"
                  >
                    <div class="user-option">
                      <span class="user-name">{{ user.userName }}</span>
                      <span class="user-nickname">{{ user.nickName }}</span>
                    </div>
                  </el-option>
                </el-select>
                <div class="form-tip">支持用户名和昵称搜索</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="选择门店"
                prop="shopId"
                class="form-item-enhanced"
              >
                <el-select
                  v-model="form.shopId"
                  placeholder="请选择门店"
                  filterable
                  clearable
                  remote
                  :remote-method="searchShop"
                  :loading="shopLoading"
                  class="enhanced-select"
                >
                  <el-option
                    v-for="shop in shopOptions"
                    :key="shop.shopId"
                    :label="shop.shopName"
                    :value="shop.shopId"
                  >
                    <div class="shop-option">
                      <span class="shop-name">{{ shop.shopName }}</span>
                      <span
                        v-if="shop.address"
                        class="shop-address"
                        :title="shop.address"
                      >
                        {{
                          shop.address.length > 15
                            ? shop.address.substring(0, 15) + "..."
                            : shop.address
                        }}
                      </span>
                    </div>
                  </el-option>
                </el-select>
                <div class="form-tip">支持门店名称搜索</div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item
            label="默认门店"
            prop="isDefault"
            class="default-shop-item"
          >
            <div class="default-shop-content">
              <el-radio-group v-model="form.isDefault">
                <el-radio
                  v-for="dict in sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                  class="enhanced-radio"
                >
                  <span class="radio-label">{{ dict.label }}</span>
                  <span v-if="dict.value === 'Y'" class="radio-tip"
                    >（将设为该用户的主要门店）</span
                  >
                </el-radio>
              </el-radio-group>
              <div v-if="form.isDefault === 'Y'" class="default-tip">
                <i class="el-icon-info"></i>
                设为默认门店后，该门店将成为用户的主要操作门店
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer-enhanced">
          <el-button @click="cancel" size="large" class="cancel-btn"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="submitForm"
            size="large"
            :loading="submitLoading"
            class="submit-btn"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="UserShopRelation">
import {
  listUserShopRelation,
  getUserShopRelation,
  delUserShopRelation,
  addUserShopRelation,
  updateUserShopRelation,
} from "@/api/ruoyi/userShopRelation";
import { listUser } from "@/api/system/user";
import { listShop } from "@/api/ruoyi/shop";

const { proxy } = getCurrentInstance();
const { sys_yes_no } = proxy.useDict("sys_yes_no");

const userShopRelationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const submitLoading = ref(false);
const userLoading = ref(false);
const shopLoading = ref(false);
const userOptions = ref([]);
const shopOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    shopId: null,
    isDefault: null,
  },
  rules: {
    userId: [{ required: true, message: "请选择用户", trigger: "change" }],
    shopId: [{ required: true, message: "请选择门店", trigger: "change" }],
    isDefault: [
      { required: true, message: "请选择是否默认门店", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 搜索用户
function searchUser(query) {
  if (query !== "") {
    userLoading.value = true;
    listUser({ userName: query, nickName: query }).then((response) => {
      userOptions.value = response.rows;
      userLoading.value = false;
    });
  } else {
    userOptions.value = [];
  }
}

// 搜索门店
function searchShop(query) {
  if (query !== "") {
    shopLoading.value = true;
    listShop({ shopName: query }).then((response) => {
      shopOptions.value = response.rows;
      shopLoading.value = false;
    });
  } else {
    shopOptions.value = [];
  }
}

// 新增：搜索区域折叠/展开
function toggleSearch() {
  showSearch.value = !showSearch.value;
}

/** 查询用户门店关联信息列表 */
function getList() {
  loading.value = true;
  listUserShopRelation(queryParams.value).then((response) => {
    userShopRelationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
  userOptions.value = [];
  shopOptions.value = [];
}

// 表单重置
function reset() {
  form.value = {
    relationId: null,
    userId: null,
    shopId: null,
    isDefault: null,
    createTime: null,
    updateTime: null,
  };
  proxy.resetForm("userShopRelationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.relationId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户门店关联信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _relationId = row.relationId || ids.value;
  getUserShopRelation(_relationId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改用户门店关联信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userShopRelationRef"].validate((valid) => {
    if (valid) {
      submitLoading.value = true;
      if (form.value.relationId != null) {
        updateUserShopRelation(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            submitLoading.value = false;
            getList();
          })
          .catch(() => {
            submitLoading.value = false;
          });
      } else {
        addUserShopRelation(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            submitLoading.value = false;
            getList();
          })
          .catch(() => {
            submitLoading.value = false;
          });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _relationIds = row.relationId || ids.value;
  proxy.$modal
    .confirm(
      '是否确认删除用户门店关联信息编号为"' + _relationIds + '"的数据项？'
    )
    .then(function () {
      return delUserShopRelation(_relationIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/userShopRelation/export",
    {
      ...queryParams.value,
    },
    `userShopRelation_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style scoped>
/* 搜索卡片样式 */
.search-card {
  /* margin-bottom: 16px; */
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: #303133;
}

.collapse-btn {
  padding: 0;
  font-size: 14px;
  color: #606266;
}

/* 对话框样式优化 */
.user-shop-dialog {
  --dialog-header-bg: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.user-shop-dialog :deep(.el-dialog__header) {
  background: var(--dialog-header-bg);
  margin: 0;
  padding: 16px 20px;
  border-radius: 8px 8px 0 0;
}

.user-shop-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 16px;
}

.user-shop-dialog :deep(.el-dialog__headerbtn) {
  top: 16px;
}

.user-shop-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

.dialog-content {
  padding: 20px 0 0;
}

.dialog-form {
  max-width: 100%;
}

.form-item-enhanced {
  margin-bottom: 24px;
}

.form-item-enhanced :deep(.el-form-item__label) {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.enhanced-select {
  width: 100%;
}

.enhanced-select :deep(.el-input__inner) {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.enhanced-select :deep(.el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.user-option,
.shop-option {
  display: flex;
  flex-direction: column;
  padding: 4px 0;
}

.user-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.user-nickname {
  font-size: 12px;
  color: #909399;
}

.shop-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.shop-address {
  font-size: 12px;
  color: #909399;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.default-shop-item {
  margin-bottom: 16px;
}

.default-shop-content {
  width: 100%;
}

.enhanced-radio {
  margin-right: 20px;
  margin-bottom: 8px;
}

.radio-label {
  font-weight: 500;
  color: #303133;
}

.radio-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
}

.default-tip {
  background: #f0f9ff;
  border: 1px solid #e1f5fe;
  border-radius: 4px;
  padding: 8px 12px;
  margin-top: 8px;
  font-size: 12px;
  color: #1890ff;
  display: flex;
  align-items: center;
}

.default-tip i {
  margin-right: 6px;
  font-size: 14px;
}

.dialog-footer-enhanced {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.cancel-btn,
.submit-btn {
  min-width: 100px;
  border-radius: 6px;
  font-weight: 500;
}

.cancel-btn {
  border-color: #dcdfe6;
  color: #606266;
}

.cancel-btn:hover {
  border-color: #c0c4cc;
  color: #606266;
  background-color: #f5f7fa;
}

.submit-btn {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  border: none;
}

.submit-btn:hover {
  background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-shop-dialog {
    width: 90vw !important;
    margin: 5vh auto;
  }

  .dialog-form :deep(.el-form-item__label) {
    width: 80px !important;
  }

  .enhanced-radio {
    display: block;
    margin-right: 0;
    margin-bottom: 12px;
  }
}

/* 加载状态优化 */
.form-item-enhanced :deep(.el-loading-spinner .circular) {
  width: 20px;
  height: 20px;
}

/* 错误状态样式 */
.form-item-enhanced :deep(.el-form-item__error) {
  font-size: 12px;
  padding-top: 4px;
}

/* 选中状态优化 */
.enhanced-select :deep(.el-select-dropdown__item.selected) {
  background-color: #f5f7fa;
  color: #409eff;
  font-weight: 500;
}

/* 过渡动画 */
.user-shop-dialog :deep(.el-dialog) {
  transition: all 0.3s ease;
}

.submit-btn {
  transition: all 0.3s ease;
}
</style>
